//
//  WmcHomeFooterView.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/3/2.
//

import UIKit
import YPBedrock
import RxRelay

public extension WmcButtonItemType {
    /// 按钮类型
    enum HomeFooter {
        /// 本地相册
        case localAlbum

        /// 水印选择
        case watermark

        /// 翻转
        case flip

        /// 云相册
        case cloudAlbum

        /// 暂停/开始视频录制
        case pauseVideoRecording

        /// 滤镜
        case filter

        /// 物体识别（AI功能）
        case objectRecognition

        /// 空白占位（用于布局，无特殊效果）
        case placeholder
        
        /// 撤销
        case undo

        /// 自定义
        case custom(view: UIView)
    }

    /// 按钮类型
    enum HomeCenter {
        /// 默认
        case `default`

        /// 自定义
        case custom(view: UIView)
    }
}

extension WmcHomeFooterView {
    enum CombinePhotoGuideState {
        case none
        case stepOne
        case stepTwo
    }
}

// MARK: - [WmcHomeFooterView]

class WmcHomeFooterView: WmcBaseView {
    /// 本地相册
    lazy var localAlbumBtn: WmcHomeLocalBtn = {
        let btn = WmcHomeLocalBtn.create()
        btn.isEnabled = false
        return btn
    }()
    /// 水印
    lazy var watermarkBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "水印", image: "home_tool_watermark".wmc_image)
        return btn
    }()
    /// 翻转
    lazy var flipBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "翻转", image: "home_tool_flip".wmc_image)
        return btn
    }()
    
    /// 拍照按钮
    private(set) lazy var actionBtn: UIButton = {
        let btn = UIButton()
//        btn.setImage("home_tool_action".wmc_image, for: .normal)
        btn.setTitleColor(UIColor.wmc_white_FFFFFF, for: .normal)
        btn.titleLabel?.font = 15.wmc_font(weight: .medium)
        btn.titleLabel?.numberOfLines = 0
        return btn
    }()

    /// 视频录制按钮
    lazy var videoActionBtn: WmcHomeVideoBtn = {
        let btn = WmcHomeVideoBtn()
        return btn
    }()
    /// 团队相册
    lazy var cloudAlbumBtn: WmcSynchronousStatusView = {
        let btn = WmcSynchronousStatusView()
        return btn
    }()

    lazy var pauseVideoRecordBtn: WmcHomePauseRecordBtn = {
        let btn = WmcHomePauseRecordBtn.Create()
        return btn
    }()

    lazy var filterBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "滤镜", image: "home_tool_filter".wmc_image)
        return btn
    }()

    lazy var objectRecognitionBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "识别物体", image: "home_ai_recognize_icon".wmc_image)
        btn.label.font = 12.yp.uiFont(weight: .medium)
        btn.label.textColor = .wmc_grayH8_8A8A99
        return btn
    }()
    
    /// 撤销
    lazy var undoBtn: WmcTopImgBottomTextBtn = {
        let btn = createTopImgBottomTextBtn(title: "撤销", image: "icon_undo_32".wmc_image)
        return btn
    }()


    lazy var leftStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        stackView.spacing = 10
        return stackView
    }()

    lazy var rightStackView: UIStackView = {
        let stackView = UIStackView()
        stackView.axis = .horizontal
        stackView.distribution = .equalSpacing
        stackView.spacing = 8
        return stackView
    }()

    lazy var watermarkRedPoint: UIView = {
        let view = UIView()
        view.backgroundColor = .red
        view.layer.cornerRadius = 4
        return view
    }()

    lazy var centerLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 0
        return label
    }()

    lazy var topView: UIView = {
        let view = UIView()
        return view
    }()

    lazy var teamBgView: UIView = {
        let view = UIView()
        view.backgroundColor = .wmc_grayH13_ACAEAF
        view.layer.cornerRadius = 2
        view.addSubview(syncLabel)
        syncLabel.snp.makeConstraints { make in
            make.left.equalTo(5)
            make.right.equalTo(-5)
            make.top.equalTo(4)
            make.bottom.equalTo(-4)
        }
        return view
    }()

    lazy var syncLabel: UILabel = {
        let label = UILabel()
        label.text = "点击同步到云相册>"
        label.font = 12.wmc_font
        label.textColor = .white
        return label
    }()

    /// 中间视图承载容器
    lazy var centerContainerView: UIView = {
        let view = UIView()
        return view
    }()
    
    /// 边拍边拼模式的标题view
    private(set) lazy var titleView: WmcCombinePhotoTitleView = {
        let view = WmcCombinePhotoTitleView()
        // 默认隐藏
        view.isHidden = true
        return view
    }()
    /// 引导手指
    private lazy var fingerView: UIImageView = {
        let imgView = UIImageView()
        imgView.image = "icon_finger_43".wmc_image
        imgView.isHidden = true
        imgView.isUserInteractionEnabled = false
        return imgView
    }()

    /// 触发的回调
    var hitTestBlock: YPBlock.Empty?

    /// 背景是否透明状态
    var isTransparent: Bool = false

    /// 功能模式
    var functionMode: WmcButtonItemType.HomeFunctionMode = .photo {
        didSet {
            updateTitleViewHidden()
        }
    }

    /// 视频录制状态
    var videoRecordState: WmcHomeVC.VideoRecordState = .stop
    
    /// 边拍边拼状态
    var photoCombineState: WmcHomeVC.PhotoCombineState = .stop {
        didSet {
            if photoCombineState != oldValue {
                updateTitleViewHidden()
                reloadItems()
            }
        }
    }
    /// 拼图模式标题
    var combinePhotoTitle: String = "" {
        didSet {
            titleView.title = combinePhotoTitle
        }
    }
    
    /// 是否可以拼图
    var canCombine: Bool = false {
        didSet {
            titleView.okBtn.isEnabled = canCombine
        }
    }
    /// 拼图引导状态
    var cpGuideState: CombinePhotoGuideState = .none
    
    
    /// 拼图回调
    let combinePhotoAction: PublishRelay<Void> = .init()
    /// 取消拼图回调
    let cancelCombinePhoto: PublishRelay<Void> = .init()

    /// 通用创建一种样式的按钮
    func createTopImgBottomTextBtn(title: String, image: UIImage) -> WmcTopImgBottomTextBtn {
        let btn = WmcTopImgBottomTextBtn(title: title, image: image)
        btn.font = 12.yp.uiFont(weight: .medium)
        btn.imgTextSpacing = 6
        btn.imgSize = 36
        btn.textColor = .black
        btn.yp.layoutWidthEqual(50.wmc_autoHor)
        return btn
    }

    override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
        hitTestBlock?()

        let superHit = super.hitTest(point, with: event)
        guard bounds.contains(point) else { return superHit }
        for view in subviews {
            if view.frame.contains(point) {
                if !(superHit is UIStackView) {
                    return superHit
                }
            }
        }
        return nil
    }

    override func config() {
        // 刷新正常左按钮
        YPWmcDrivingManager.shared.home_reloadToolLeftMenuItemsBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.reloadLeftItems()
        }
        // 刷新正常右按钮
        YPWmcDrivingManager.shared.home_reloadToolRightMenuItemsBlock = { [weak self] in
            guard let weakSelf = self else { return }
            weakSelf.reloadRightItems()
        }
    }

    // MARK: UI
    override func makeUI() {
        addSubview(topView)
        addSubview(actionBtn)
        addSubview(videoActionBtn)
        addSubview(centerLabel)
        addSubview(leftStackView)
        addSubview(rightStackView)

        // 是否显示团队同步
        var isShowTeamAsync = true
        if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
            let isShow = homeDelegate.toolAsyncTeamTipShow(.current,
                                                           isTransparent: isTransparent,
                                                           functionMode: functionMode,
                                                           videoRecordState: videoRecordState)
            isShowTeamAsync = isShow
        }

        if isShowTeamAsync {
            topView.addSubview(teamBgView)
            teamBgView.snp.makeConstraints { make in
                make.centerX.centerY.equalToSuperview()
            }
        }
        // 添加手指
        addSubview(fingerView)
        fingerView.snp.makeConstraints { make in
            make.left.equalTo(actionBtn.snp.centerX).offset(-5.0)
            make.bottom.equalTo(actionBtn).offset(25.0)
            make.width.height.equalTo(55.0)
        }
        // 标题view
        topView.addSubview(titleView)
        titleView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.height.equalTo(44.0.wmc_autoVer)
        }
        self.canCombine = false
        
        watermarkBtn.addSubview(watermarkRedPoint)

        topView.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.bottom.equalTo(actionBtn.snp.top)
        }

        actionBtn.snp.makeConstraints { make in
            make.centerX.equalToSuperview()
            make.centerY.equalToSuperview().offset(8.0.wmc_autoHor)
            make.size.equalTo(70)
        }

        videoActionBtn.snp.makeConstraints { make in
            make.edges.equalTo(actionBtn)
        }

        addSubview(centerContainerView)
        centerContainerView.snp.makeConstraints { make in
            make.edges.equalTo(actionBtn)
        }

        addSubview(centerLabel)

        centerLabel.snp.makeConstraints { make in
            make.centerX.equalTo(actionBtn)
            make.top.equalTo(actionBtn.snp.bottom).offset(12)
        }

        leftStackView.snp.makeConstraints { make in
            make.left.equalTo(22)
            make.centerY.equalTo(actionBtn)
            make.height.equalTo(60)
            make.right.equalTo(actionBtn.snp.left).offset(-22)
        }

        rightStackView.snp.makeConstraints { make in
            make.left.equalTo(actionBtn.snp.right).offset(22)
            make.centerY.equalTo(actionBtn)
            make.height.equalTo(leftStackView)
            make.right.equalTo(-22)
        }

        watermarkBtn.addSubview(watermarkRedPoint)

        watermarkRedPoint.snp.makeConstraints { make in
            make.width.height.equalTo(8)
            make.top.equalTo(-1)
            let offset = (watermarkBtn.imgSize ?? 0) / 2
            make.centerX.equalTo(watermarkBtn.snp.centerX).offset(offset)
        }

        reloadItems()
    }
    
    // MARK: Bind Action
    override func bindViewAction() {
        super.bindViewAction()
        // 点击完成
        titleView.okAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.photoCombineState = .stop
            self.combinePhotoAction.accept(())
        }).disposed(by: rx.disposeBag)
        // 点击取消
        titleView.cancelAction.subscribe(onNext: {
            [weak self] in
            guard let self = self else { return }
            self.cancelCombinePhoto.accept(())
        }).disposed(by: rx.disposeBag)
    }

    /// 更新云相册按钮状态
    func updateCloudAlbumBtnStatus() {
        cloudAlbumBtn.setDefaultStatus()

        if let isShowed: Bool = WmcUserdefault.object(forKey: .Tips.Home.watermarkSelectBtnPoint) {
            watermarkRedPoint.isHidden = isShowed
        } else {
            watermarkRedPoint.isHidden = false
        }
    }

    func isTakePhotoModel() -> Bool {
        var result = false
        switch functionMode {
        case .photo:
            result = true
        default:
            result = false
        }
        return result
    }

    /// 刷新正常左按钮
    func reloadLeftItems() {
        var defaultCase: [WmcButtonItemType.HomeFooter] = []
        switch functionMode {
        case .rebarCount:
            defaultCase = [
                .localAlbum,
            ]
        case .photoAndCombine:
            switch photoCombineState {
            case .being:
                defaultCase = [.undo, .watermark]
            case .stop:
                defaultCase = [.localAlbum, .watermark]
            }
        default:
            switch videoRecordState {
            case .stop:
                defaultCase = [
                    .localAlbum, .watermark,
                ]
            case .being,
                 .pause:
                defaultCase = [
                    .placeholder, .flip,
                ]
            }
        }
        if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
            let caseList = homeDelegate.toolLeftMenuList(.current,
                                                         isTransparent: isTransparent,
                                                         functionMode: functionMode,
                                                         videoRecordState: videoRecordState,
                                                         defaultList: defaultCase)
            defaultCase = caseList
        }
        let views = toItemList(caseList: defaultCase)
        leftStackView.yp.arrangedSubviews = views
    }

    func reloadCenterItem() {
        var defaultCase: WmcButtonItemType.HomeCenter = .default
        if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
            let caseList = homeDelegate.toolCenterMenuItem(.current,
                                                           isTransparent: isTransparent,
                                                           functionMode: functionMode,
                                                           videoRecordState: videoRecordState,
                                                           defaultItem: defaultCase)
            defaultCase = caseList
        }
        teamBgView.isHidden = true
        switch functionMode {
        case .photo,
             .photoAndCombine,
             .video:
            teamBgView.isHidden = false
        default: break
        }
        switch defaultCase {
        case .default:
            centerContainerView.isHidden = true
            switch functionMode {
            case .photo,
                 .photoAndCombine,
                 .rebarCount:
                actionBtn.isHidden = false
                videoActionBtn.isHidden = true
            case .video:
                actionBtn.isHidden = true
                videoActionBtn.isHidden = false
            default: break
            }
        case let .custom(view: view):
            actionBtn.isHidden = true
            videoActionBtn.isHidden = true
            // 展示容器视图
            centerContainerView.isHidden = false
            centerContainerView.subviews.forEach { view in
                view.removeFromSuperview()
            }
            centerContainerView.addSubview(view)
            view.snp.makeConstraints { make in
                make.edges.equalToSuperview()
            }
            view.layer.removeAllAnimations()
            layoutIfNeeded()
        }
    }

    /// 刷新正常右按钮
    func reloadRightItems() {
        var defaultCase: [WmcButtonItemType.HomeFooter] = []
        switch functionMode {
        case .rebarCount:
            defaultCase = [
                .objectRecognition,
            ]
        case .photoAndCombine:
            switch photoCombineState {
            case .being:
                defaultCase = [.flip, .placeholder]
            case .stop:
                defaultCase = [.flip, .cloudAlbum]
            }
        default:
            switch videoRecordState {
            case .stop:
                defaultCase = [
                    .flip, .cloudAlbum,
                ]
            case .being,
                 .pause:
                defaultCase = [
                    .pauseVideoRecording, .placeholder,
                ]
            }
        }
        if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
            let caseList = homeDelegate.toolRightMenuList(.current,
                                                          isTransparent: isTransparent,
                                                          functionMode: functionMode,
                                                          videoRecordState: videoRecordState,
                                                          defaultList: defaultCase)
            defaultCase = caseList
        }
        let views = toItemList(caseList: defaultCase)
        rightStackView.yp.arrangedSubviews = views
    }

    /// 转换成按钮实体
    func toItemList(caseList: [WmcButtonItemType.HomeFooter]) -> [UIView] {
        var items: [UIView] = []
        caseList.forEach { cas in
            switch cas {
            case .localAlbum:
                items.append(localAlbumBtn)
            case .watermark:
                items.append(watermarkBtn)
            case .flip:
                items.append(flipBtn)
            case .cloudAlbum:
                items.append(cloudAlbumBtn)
            case .placeholder:
                let view = UIView()
                view.yp.layoutWidthEqual(50.wmc_autoHor)
                items.append(view)
            case .pauseVideoRecording:
                items.append(pauseVideoRecordBtn)
            case .filter:
                items.append(filterBtn)
            case .objectRecognition:
                items.append(objectRecognitionBtn)
            case let .custom(view):
                items.append(view)
            case .undo:
                items.append(undoBtn)
            }
        }
        return items
    }

    /// 重载按钮
    func reloadItems() {
        if isTransparent { // 透明
            localAlbumBtn.setTintColor(.white)
            watermarkBtn.setTintColor(.white)
            flipBtn.setTintColor(.white)
            filterBtn.setTintColor(.white)
            cloudAlbumBtn.style = .white
            videoActionBtn.setLineColor(.white)
            pauseVideoRecordBtn.setTintColor(.white)
            
            undoBtn.setTintColor(.white)
        } else {
            localAlbumBtn.setTintColor(.wmc_grayH8_8A8A99)

            watermarkBtn.setImageTintColor(.wmc_grayH2_323233)
            watermarkBtn.setTextColor(.wmc_grayH8_8A8A99)

            flipBtn.setImageTintColor(.wmc_grayH2_323233)
            flipBtn.setTextColor(.wmc_grayH8_8A8A99)

            filterBtn.setImageTintColor(.wmc_grayH2_323233)
            filterBtn.setTextColor(.wmc_grayH8_8A8A99)

            filterBtn.setTintColor(.wmc_grayH2_323233)
            cloudAlbumBtn.style = .blue
            videoActionBtn.setLineColor(.wmc_grayH8_8A8A99)
            pauseVideoRecordBtn.setTintColor(.wmc_grayH8_8A8A99)
            // 撤销按钮
            undoBtn.setImageTintColor(.wmc_grayH2_323233)
            undoBtn.setTextColor(.wmc_grayH8_8A8A99)
        }
        updateTakePhotoButton()
        reloadLeftItems()
        reloadCenterItem()
        reloadRightItems()
        // 快门文案
        if let homeDelegate = YPWmcManager.shared.uiDelegate.homeDelegate {
            let attText = homeDelegate.toolShutterTipAttributedText(.current,
                                                                    isTransparent: isTransparent,
                                                                    functionMode: functionMode,
                                                                    videoRecordState: videoRecordState)
            centerLabel.attributedText = attText
        }
    }

    /// 切换模式
    func switchMode(_ mode: WmcButtonItemType.HomeFunctionMode) {
        functionMode = mode
        // 结束录制
        switchVideoRecordingState(.stop)
    }

    /// 切换状态
    func switchVideoRecordingState(_ state: WmcHomeVC.VideoRecordState) {
        videoRecordState = state
        switch state {
        case .stop:
            videoActionBtn.setState(.normal)
            pauseVideoRecordBtn.recordState = .pause
        case .being,
             .pause:
            videoActionBtn.setState(.recording)
        }
        reloadLeftItems()
        reloadCenterItem()
        reloadRightItems()
    }

    /// 更新同步状态的文案
    func updateSyncTeamStatus(count: Int) {
        if count > 0 {
            teamBgView.backgroundColor = .wmc_grayH3_505050
            syncLabel.text = "拍照同步\(count)个团队>"
            syncLabel.snp.updateConstraints { make in
                make.left.equalTo(8)
                make.right.equalTo(-8)
            }
        } else {
            teamBgView.backgroundColor = .wmc_grayH13_ACAEAF
            syncLabel.text = "点击同步到云相册>"
            syncLabel.snp.updateConstraints { make in
                make.left.equalTo(5)
                make.right.equalTo(-5)
            }
        }
    }
}

extension WmcHomeFooterView {
    
    /// 更新titleView显示隐藏
    private func updateTitleViewHidden() {
        switch functionMode {
        case .photoAndCombine:
            switch photoCombineState {
            case .being:
                titleView.isHidden = false
            case .stop:
                titleView.isHidden = true
            }
        default:
            titleView.isHidden = true
        }
    }
    
    /// 更新拍照按钮UI
    func updateTakePhotoButton() {
        if isTransparent {
            actionBtn.setBackgroundImage("home_tool_action".wmc_image.yp.set(tintColor: UIColor.white), for: .normal)
        } else {
            actionBtn.setBackgroundImage("home_tool_action".wmc_image.yp.set(tintColor: UIColor.wmc_mainTheme), for: .normal)
        }
        switch functionMode {
        case .photoAndCombine:
            switch cpGuideState {
            case .none:
                actionBtn.setTitle(nil, for: .normal)
            case .stepOne:
                actionBtn.setTitle("马上拍", for: .normal)
            case .stepTwo:
                actionBtn.setTitle("再来\n一张", for: .normal)
            }
            fingerView.isHidden = cpGuideState == .none
        default:
            actionBtn.setTitle(nil, for: .normal)
            fingerView.isHidden = true
        }
    }
}
